import axios from "axios";
import { router } from "./router";

const http = axios.create({
  baseURL: import.meta.env.VITE_SEREVER_HOST as string,
  withCredentials: true,
});
http.interceptors.request.use(
  (config) => {
    if (localStorage.token) {
      config.headers.Authorization = "Bearer " + localStorage.token || "";
    }
    return config;
  },
  (e) => {
    return Promise.reject(e);
  }
);
http.interceptors.response.use(
  (res) => {
    return res;
  },
  (e) => {
    if (e.response.status == 401) {
      router.push("/login");
      localStorage.clear();
      return Promise.reject(e);
    }
    throw e;
  }
);

export { http };
